'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/auth-context'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { 
  ExternalLink, 
  Heart, 
  User,
  Calendar,
  Tag
} from 'lucide-react'
import { StarDisplay } from '@/components/ui/star-rating'
import Link from 'next/link'
import { type StoredFavorite, type StoredTool } from '@/lib/database'

interface FavoriteWithTool extends StoredFavorite {
  tool: StoredTool
}

export function MyFavorites() {
  const { user: authUser, loading: authLoading } = useAuth()
  const [favorites, setFavorites] = useState<FavoriteWithTool[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!authLoading && authUser) {
      fetchMyFavorites(authUser.id)
    } else if (!authLoading) {
      setLoading(false)
    }
  }, [authUser, authLoading])

  const fetchMyFavorites = async (userId: string) => {
    try {
      setLoading(true)

      // 获取用户收藏
      const favoritesResponse = await fetch(`/api/favorites?userId=${userId}`)
      const favoritesResult = await favoritesResponse.json()

      // 获取所有工具
      const toolsResponse = await fetch('/api/tools')
      const toolsResult = await toolsResponse.json()

      if (favoritesResponse.ok && toolsResponse.ok) {
        const userFavorites = favoritesResult.data || []
        const allTools = toolsResult.data || []

        // 关联收藏和工具数据
        const favoritesWithTools = userFavorites.map((favorite: StoredFavorite) => {
          const tool = allTools.find((t: StoredTool) => t.id === favorite.toolId)
          return {
            ...favorite,
            tool
          }
        }).filter((item: any) => item.tool) // 过滤掉找不到工具的收藏

        setFavorites(favoritesWithTools)
      }
    } catch (error) {
      console.error('获取收藏失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleRemoveFavorite = async (toolId: string) => {
    if (!authUser) return

    try {
      const response = await fetch(`/api/tools/${toolId}/favorite?userId=${authUser.id}`, {
        method: 'DELETE'
      })

      if (response.ok) {
        setFavorites(prev => prev.filter(fav => fav.toolId !== toolId))
      }
    } catch (error) {
      console.error('取消收藏失败:', error)
    }
  }

  if (loading) {
    return (
      <div className="space-y-4">
        {Array.from({ length: 3 }).map((_, i) => (
          <Card key={i} className="animate-pulse">
            <CardContent className="p-6">
              <div className="h-4 bg-gray-200 rounded w-1/4 mb-2"></div>
              <div className="h-3 bg-gray-200 rounded w-3/4 mb-4"></div>
              <div className="flex gap-2">
                <div className="h-8 bg-gray-200 rounded w-20"></div>
                <div className="h-8 bg-gray-200 rounded w-20"></div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2">
              <Heart className="h-5 w-5 text-red-500" />
              <div>
                <div className="text-2xl font-bold">{favorites.length}</div>
                <div className="text-sm text-gray-500">总收藏</div>
              </div>
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2">
              <Tag className="h-5 w-5 text-blue-500" />
              <div>
                <div className="text-2xl font-bold">
                  {new Set(favorites.map(f => f.tool.category.name)).size}
                </div>
                <div className="text-sm text-gray-500">分类数</div>
              </div>
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2">
              <Calendar className="h-5 w-5 text-green-500" />
              <div>
                <div className="text-2xl font-bold">
                  {favorites.length > 0 ? 
                    Math.ceil((Date.now() - new Date(favorites[favorites.length - 1].createdAt).getTime()) / (1000 * 60 * 60 * 24))
                    : 0
                  }
                </div>
                <div className="text-sm text-gray-500">天前最后收藏</div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 收藏列表 */}
      <div className="space-y-4">
        {favorites.length === 0 ? (
          <Card>
            <CardContent className="p-12 text-center">
              <Heart className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">
                还没有收藏任何工具
              </h3>
              <p className="text-gray-500 mb-4">
                浏览工具并收藏您喜欢的内容
              </p>
              <Link href="/">
                <Button>
                  浏览工具
                </Button>
              </Link>
            </CardContent>
          </Card>
        ) : (
          favorites.map((favorite) => (
            <Card key={favorite.id}>
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <CardTitle className="flex items-center gap-2">
                      {favorite.tool.title}
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                        {favorite.tool.category.icon} {favorite.tool.category.name}
                      </span>
                    </CardTitle>
                    <CardDescription className="mt-1">
                      {favorite.tool.description}
                    </CardDescription>
                  </div>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleRemoveFavorite(favorite.toolId)}
                    className="text-red-600 hover:text-red-700"
                  >
                    <Heart className="h-4 w-4 mr-2 fill-current" />
                    取消收藏
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {/* 工具信息 */}
                  <div className="flex items-center gap-4 text-sm text-gray-600">
                    <div className="flex items-center gap-1">
                      <User className="h-4 w-4" />
                      <span>发布者: {favorite.tool.user.name}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Calendar className="h-4 w-4" />
                      <span>收藏于: {new Date(favorite.createdAt).toLocaleDateString()}</span>
                    </div>
                  </div>

                  {/* 工具统计 */}
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div className="text-center">
                      <div className="font-semibold text-gray-900">0</div>
                      <div className="text-gray-500">访问量</div>
                    </div>
                    <div className="text-center">
                      <div className="font-semibold text-gray-900">0</div>
                      <div className="text-gray-500">收藏数</div>
                    </div>
                    <div className="text-center">
                      <div className="flex items-center justify-center gap-1">
                        <StarDisplay rating={0} size="sm" showValue={false} />
                        <span className="font-semibold text-gray-900">0.0</span>
                      </div>
                      <div className="text-gray-500">评分</div>
                    </div>
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex gap-2">
                    {favorite.tool.isDeployed ? (
                      <Button
                        size="sm"
                        onClick={() => window.open(`/tools/deployed/${favorite.tool.id}?pure=true`, '_blank')}
                      >
                        <ExternalLink className="h-4 w-4 mr-2" />
                        使用工具
                      </Button>
                    ) : (
                      <Button
                        size="sm"
                        onClick={() => window.open(favorite.tool.url, '_blank')}
                      >
                        <ExternalLink className="h-4 w-4 mr-2" />
                        访问网站
                      </Button>
                    )}
                    
                    <Link href={`/tools/${favorite.tool.id}`}>
                      <Button size="sm" variant="outline">
                        查看详情
                      </Button>
                    </Link>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>
    </div>
  )
}
